<template>
    <div class="wrap-stock-detail">
        <main>
            <n-card :title="$t('form.infoTrace')">
                <n-steps :current="currentStatus" status="process">
                    <n-step :title="$t('form.step1')">
                        <template #icon>
                            <n-icon>
                                <Archive />
                            </n-icon>
                        </template>
                        <span>{{ $t('form.orderDate') }}:{{ props.detailInfo.data.orderDate }}</span>
                    </n-step>
                    <n-step :title="$t('form.step2')">
                        <template #icon>
                            <n-icon>
                                <LogoAlipay />
                            </n-icon>
                        </template>
                        {{ $t('form.realPrice') }}:￥{{ props.detailInfo.data.bossPay }}
                    </n-step>
                    <n-step :title="$t('form.step3')">
                        <template #icon>
                            <n-icon>
                                <GameControllerSharp />
                            </n-icon>
                        </template>
                        {{ $t('tableColumnLabel.accompanyName') }}:{{ props.detailInfo.data.accomUser?.name || $t("text.deleteAccomWarning")}}
                    </n-step>
                    <n-step :title="$t('form.step4')">
                        <template #icon>
                            <n-icon>
                                <CheckmarkDoneCircleSharp />
                            </n-icon>
                        </template>
                        {{ $t('form.finalPrice') }}:￥{{ props.detailInfo.data.bossPay }}
                    </n-step>
                </n-steps>
            </n-card>
            <n-card :title="$t('form.accompanyInfo')" v-if="props.detailInfo.data.accomUser?.id">
                <n-descriptions label-placement="top" bordered :column="4">
                    <n-descriptions-item :label="$t('tableColumnLabel.accompanyName')">
                        {{ props.detailInfo.data.accomUser?.name }}
                    </n-descriptions-item>
                    <n-descriptions-item :label="$t('form.accomBirthDay')">
                        {{ props.detailInfo.data.accomUser?.birthDay }}
                    </n-descriptions-item>
                    <n-descriptions-item :label="$t('tableColumnLabel.price')">
                        ￥{{ props.detailInfo.data.accomUser?.price }}
                    </n-descriptions-item>
                    <n-descriptions-item :label="$t('tableColumnLabel.discountPrice')">
                        {{ props.detailInfo.data.accomUser?.discount }}
                    </n-descriptions-item>
                    <n-descriptions-item :label="$t('tableColumnLabel.gameRank')">
                        {{ props.detailInfo.data.accomUser?.rank }}
                    </n-descriptions-item>
                    <n-descriptions-item :label="$t('tableColumnLabel.sex')">
                        {{ props.detailInfo.data.accomUser?.sex === '1' ? $t('unit.man') : $t('unit.woman') }}
                    </n-descriptions-item>
                    <n-descriptions-item :label="$t('form.accomSignBoard')">
                        {{ props.detailInfo.data.accomUser?.signboard }}
                    </n-descriptions-item>
                    <n-descriptions-item :label="$t('form.accomBusinessType')">
                        {{ props.detailInfo.data.accomUser?.type }}
                    </n-descriptions-item>
                    <n-descriptions-item :label="$t('tableColumnLabel.introcution')" :span="4">
                        {{ props.detailInfo.data.accomUser?.introduction }}
                    </n-descriptions-item>
                </n-descriptions>
            </n-card>
            <n-card :title="$t('form.orderInfo')">
                <n-descriptions label-placement="top" bordered :column="4">
                    <n-descriptions-item :label="$t('form.accomBusinessType')">
                        {{ props.detailInfo.data.accomType }}
                    </n-descriptions-item>
                    <n-descriptions-item :label="$t('tableColumnLabel.bossName')">
                        {{ props.detailInfo.data.bossName }}
                    </n-descriptions-item>
                    <n-descriptions-item :label="$t('tableColumnLabel.bossPay')">
                        ￥{{ props.detailInfo.data.bossPay }}
                    </n-descriptions-item>
                    <n-descriptions-item :label="$t('tableColumnLabel.bossTel')">
                        {{ props.detailInfo.data.bossTel }}
                    </n-descriptions-item>
                    <n-descriptions-item :label="$t('tableColumnLabel.proxyUserName')">
                        {{ props.detailInfo.data.proxyUserName }}
                    </n-descriptions-item>
                    <n-descriptions-item :label="$t('tableColumnLabel.proxyUserTel')">
                        {{ props.detailInfo.data.proxyUserqq }}
                    </n-descriptions-item>
                    <n-descriptions-item :label="$t('form.orderRemark')">
                        {{ props.detailInfo.data.remark || $t('text.noDate') }}
                    </n-descriptions-item>
                    <n-descriptions-item :label="$t('form.orderStatus')">
                        {{ statusMap[props.detailInfo.data.status as keyof typeof statusMap] || 'unKnown' }}
                    </n-descriptions-item>
                    <n-descriptions-item :label="$t('tableColumnLabel.accompanyTime')" :span="4">
                        {{ props.detailInfo.data.startTime }} —— {{ props.detailInfo.data.endTime }}
                    </n-descriptions-item>
                </n-descriptions>
            </n-card>
            <n-card :title="$t('form.renewalInfo')" v-if="props.detailInfo.type === 'charge' && props.detailInfo.data.status === '2'">
                <n-form :model="chargeForm" label-placement="left" label-align="right" label-width="120"
                    require-mark-placement="right-hanging">
                    <n-grid :cols="24" :x-gap="24">
                        <n-form-item-gi :span="12" :label="$t('form.endTimeUpdate')" path="accomType" style="width:100%">
                            <n-date-picker v-model:formatted-value="chargeForm.newEndTime" fomat="yyyy-MM-dd HH:mm"
                                value-format="yyyy-MM-dd HH:mm" type="datetime" clearable />
                        </n-form-item-gi>
                        <n-form-item-gi :span="12" :label="$t('form.renewalPay')" path="bossPay">
                            <n-input-number v-model:value="chargeForm.chargePay" :min="0" :max="50000"
                                style="width:100%">
                                <template #prefix>
                                    ￥
                                </template>
                            </n-input-number>
                        </n-form-item-gi>
                    </n-grid>
                </n-form>
            </n-card>
        </main>
        <footer>
            <n-button @click="returnBack">{{ $t('button.returnBack') }}</n-button>
            <template v-if="detailInfo.type === 'charge'">
                <n-button v-if="currentStatus === 1" type="primary" :loading="loading" :disabled="loading"
                    @click="oepnOrder">{{ $t('button.openOrder') }}</n-button>
                <n-button v-if="currentStatus === 3" type="primary"
                   :loading="loading"
                   :disabled="loading"
                   @click="startLongGame">
                   {{ $t('button.renewal') }}
                </n-button>
            </template>
        </footer>
    </div>
</template>

<script setup lang='ts'>
import { LogoAlipay, Archive, GameControllerSharp, CheckmarkDoneCircleSharp } from '@vicons/ionicons5';
import { useDialog, useMessage } from 'naive-ui';
import { changeOrderStatus,uploadOrder } from '@/api/backend/order';
import { getByTag } from '@/api/backend/admin';
import i18n from '@/locales';
const { t } = i18n.global;
const statusMap = {
    '0':t('form.step1'),
    '1':t('form.step2'),
    '2':t('form.step3'),
    '3':t('form.step4')
}

const dialog = useDialog();
const emit = defineEmits<{
    (e: 'toList'): void;
}>();
const props = defineProps<{
    detailInfo: {
        type: 'view' | 'add' | 'charge' | null;
        data: Partial<OrderVO>;
    }
}>();
const currentStatus = ref<number | null>(null)
watch(() => props.detailInfo.data, (newVal) => {
    currentStatus.value = Number(newVal?.status ?? 0) + 1;
}, {
    immediate: true
})
const message = useMessage();
const chargeForm = reactive({
    chargePay: 0,
    newEndTime: props.detailInfo.data.endTime
})
const loading = ref(false);
// 初始化字典
const userTypeDict = reactive<{
    label: string;
    value: string;
}[]>([]);
const permissionDict = reactive<{
    label: string;
    value: string;
}[]>([]);
const cooperationModeDict = reactive<{
    label: string;
    value: string;
}[]>([]);
const initDict = async () => {
    try {
        const [res1, res2, res3] = await Promise.all([getByTag('userType'), getByTag('permission'), getByTag('cooperationMode')]);
        userTypeDict.length = 0; // 清空数组
        permissionDict.length = 0; // 清空数组
        cooperationModeDict.length = 0; // 清空数组
        res3.data.forEach((item: Dict) => {
            cooperationModeDict.push({
                label: item.label,
                value: item.value
            });
        });
        res1.data.forEach((item: Dict) => {
            userTypeDict.push({
                label: item.label,
                value: item.value
            });
        });
        res2.data.forEach((item: Dict) => {
            permissionDict.push({
                label: item.label,
                value: item.value
            });
        });
    } catch (error) {
        message.error(`获取字典失败-${error}`);
    }
};
initDict()

const returnBack = () => {
    emit('toList');
}
// 开单
const oepnOrder = async () => {
    dialog.warning({
        title: '警告',
        content: '您确定开单吗？一旦开单，订单无法修改',
        positiveText: '确定',
        negativeText: '不确定',
        draggable: true,
        onPositiveClick: async () => {
            try {
                const response = await changeOrderStatus('2',props.detailInfo.data.id!);
                if (response.code !== 200) throw new Error(response.message);
                currentStatus.value = 3;
                message.success('开单成功！');
            } catch (error) {
                message.error(`开单失败！: ${error}`);
            } finally {
                // refreshList();
                loading.value = false;
            }
        },
        onNegativeClick: () => {
            message.error('取消')
        }
    })
}
// 续陪
const startLongGame = async ()=>{
    if(!chargeForm.newEndTime || !chargeForm.chargePay) return message.error('请填写续陪信息！');
    try {
        loading.value = true;
        const pay = chargeForm.chargePay + (props.detailInfo.data.bossPay!);
        const res = await uploadOrder(props.detailInfo.data.id!, chargeForm.newEndTime, pay);
        if(res.code !== 200) throw new Error(res.message);
        returnBack();
        message.success('续陪成功！');
    } catch (error) {
        message.error(error instanceof Error ? error.message : '服务端错误！')
    } finally {
        loading.value = false;
    }
}
</script>
<style scoped lang='scss'>
.wrap-stock-detail {
    display: grid;
    grid-template-rows: 90% 10%;
    height: 100%;
    overflow: hidden;

    main {
        padding: 48px 24px;
        overflow: hidden;
        display: flex;
        flex-direction: column;
        height: calc(100% - 96px);
        overflow: auto;
        gap: 1rem;
    }

    footer {
        height: 100%;
        width: 100%;
        background: rgba(255, 255, 255, 0.2);
        /* 半透明背景 */
        backdrop-filter: blur(10px);
        /* 背景模糊 */
        -webkit-backdrop-filter: blur(10px);
        /* 兼容性前缀 */
        border-top: 1px solid #E7E7E7;
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 1rem;
    }
}
</style>